package com.tiandang.controller;

import com.tiandang.config.SessionMap;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tiandang.core.model.Admin;
import tiandang.core.response.CommonReturnType;
import tiandang.core.service.AdminService;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AdminController {

  @Autowired
  private AdminService adminService;

  @Autowired
  protected SessionMap sessionMap;

  @RequestMapping("/")
  public String index() {
    return "welcome!";
  }

  @PostMapping("/api/login")
  public CommonReturnType login(Admin admin) {

    // 自己项目,就不注册了,用第一个登录的人作为管理员
    int adminCount = adminService.countAdmin();
    Map<String, Object> map = new HashMap<>();
    Boolean flag = false;

    if (adminCount == 0) {
      // 如果用户表为空,那保存当前的用户名和密码
      admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
      adminService.insert(admin);
      flag = true;

    } else {
      Admin a = adminService.findAdminByUsername(admin.getUsername());
      if (a == null) {
        return CommonReturnType.error(-1, "无此用户");
      } else {
        String md5Password = DigestUtils.md5Hex(admin.getPassword());
        if (md5Password.equals(a.getPassword())) {
          flag = true;
        } else {
          return CommonReturnType.error(-1, "用户名或密码错误");
        }

      }
    }

    if (flag) {
      String token = DigestUtils.md5Hex(admin.getUsername());
      map.put("username", admin.getUsername());
      map.put("token", token);

      sessionMap.register(token);
    }

    return CommonReturnType.success(map);

  }

  // 修改密码
  @PostMapping("/api/updatePassword")
  public Object updatePassword(Admin admin) {
    admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
    adminService.updatePassword(admin);
    return CommonReturnType.success();

  }
}
